package wxy;

import java.util.HashSet;
import java.util.Set;

public class LeetCode805 {
    class Solution {
        public boolean splitArraySameAverage(int[] nums) {
            int n = nums.length;
            if (n == 1) {
                return false;
            }
            int sum = 0;
            for (int num : nums) {
                sum += num;
            }
            for (int i = 0; i < n; i++) {
                nums[i] = nums[i] * n - sum;
            }
            int m = n / 2;
            Set<Integer> leftSum = new HashSet<>();
            for (int i = 1; i < (1 << m); i++) {
                int curSum = 0;
                for (int j = 0; j < m; j++) {
                    if (((1 << j) & i) != 0) {
                        curSum += nums[j];
                    }
                }
                if (curSum == 0) {
                    return true;
                }
                leftSum.add(curSum);
            }
            int rsum = 0;
            for (int i = m; i < n; i++) {
                rsum += nums[i];
            }
            for (int i = 1; i < (1 << (n - m)); i++) {
                int curSum = 0;
                for (int j = m; j < n; j++) {
                    if (((1 << (j - m)) & i) != 0) {
                        curSum += nums[j];
                    }
                }
                if (curSum == 0 || (curSum != rsum && leftSum.contains(-curSum))) {
                    return true;
                }
            }
            return false;
        }
    }
}
